package health_system.health_system.security;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;
import java.util.List;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    private final JwtAuthenticationFilter jwtAuthenticationFilter;
    private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
    private final UserDetailsService userDetailsService;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
                .csrf(csrf -> csrf.disable())
                .cors(Customizer.withDefaults())
                .exceptionHandling(exception -> exception
                        .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                )
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests(authorize -> authorize
                        // 认证相关页面和API
                        .requestMatchers("/auth/login", "/auth/register", "/login", "/register").permitAll()
                        .requestMatchers("/api/auth/**").permitAll()
                        .requestMatchers("/api/users/register").permitAll()
                        
                        // Swagger文档
                        .requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll()
                        
                        // 其他公开API
                        .requestMatchers("/api/users/check/**").permitAll()
                        .requestMatchers("/api/users/activate/**").permitAll()
                        .requestMatchers("/api/users/password/reset/**").permitAll()
                        .requestMatchers("/api/users/email/verify/**").permitAll()
                        .requestMatchers("/api/moments/media/**").permitAll()
                        .requestMatchers("/RemoteAddressForVideoChat/**").permitAll()
                        .requestMatchers("/MessagingWebSocketServer/**").permitAll()
                        .requestMatchers("/UnifiedCommunicationServer/**").permitAll()


                        // 错误页面
                        .requestMatchers("/error").permitAll()
                        
                        // 根路径和主页
                        .requestMatchers("/", "/index.html").permitAll()
                        
                        // WebSocket相关路径
                        .requestMatchers("/api/moment/ws/**", "/api/moment/ws", "/moment/ws/**", "/moment/ws").permitAll()
                        .requestMatchers("/api/test/ws/**", "/api/test/ws", "/test/ws/**", "/test/ws").permitAll()
                        .requestMatchers("/api/ws-debug/**").permitAll()
                        .requestMatchers("/api/echo/**").permitAll()
                        .requestMatchers("/api/spring-ws/**").permitAll()
                        .requestMatchers("/ChatMessageServer/**").permitAll()
                        
                        // 测试页面
                        .requestMatchers("/api/websocket-test.html", "/websocket-test.html", "/public-websocket-test.html").permitAll()
                        .requestMatchers("/echo-test.html", "/test-websocket.html", "/spring-ws-test.html").permitAll()
                        .requestMatchers("/connection-test.html", "/chat-test.html", "/media-test.html", "/file-transfer-test.html", "/social-test.html", "/friend-test.html", "/stress-test.html").permitAll()
                        
                        // 静态资源
                        .requestMatchers("/css/**", "/js/**", "/images/**", "/fonts/**", "/favicon.ico").permitAll()
                        
                        // 需要认证的页面
                        .requestMatchers("/page/**").authenticated()
                        .requestMatchers("/Post/**", "/notification/count", "/notification/all", "/notification/read/**").authenticated()
                        
                        // 其余全部需要认证
                        .anyRequest().authenticated()
                )
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                .build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(userDetailsService);
        provider.setPasswordEncoder(passwordEncoder());
        return provider;
    }

    @Bean
    public AuthenticationManager authenticationManager() {
        return new ProviderManager(authenticationProvider());
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(List.of("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth-token"));
        configuration.setExposedHeaders(List.of("x-auth-token"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}